// 请求模块

import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { Toast } from 'vant'

const request = axios.create({
    baseURL: '/dev-api',
    timeout: 5000
})

// 请求拦截器
request.interceptors.request.use((config) => {
    const { user } = store.state
    if (user) config.headers.Authorization = 'Bearer ' + user.token
    return config
})

// 响应拦截器
request.interceptors.response.use(res => {
    return res
}, async err => {
    const status = err.response.status
    if (status === 401) {
        const user = store.state.user
        if (user) {
            try {
                const { data } = await refreshTokenReq({
                    method: 'PUT',
                    url: '/v1_0/authorizations',
                    headers: {
                        Authorization: `Bearer ${user.refresh_token}`
                    }
                })

                user.token = data.data.token
                store.commit('SETUSER', user)
                return request({
                    method: err.config.method,
                    url: err.config.url,
                    data: err.config.data
                })
            } catch (err) {
                redirectLogin()
            }
        }
    }

    return Promise.reject(err)
});

function redirectLogin() {
    router.replace({
        name: 'login',
        query: {
            redirect: router.currentRoute.fullPath
        }
    })
}

const refreshTokenReq = axios.create({
    baseURL: '/dev-api',
    timeout: 5000
})

export default request
